package com.zrc.japktool.ui;

import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.StackPane;
import javafx.fxml.FXMLLoader;

import java.io.IOException;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class MainController {

    @FXML
    private TabPane mainTabPane;
    @FXML
    private StackPane stackPane;
    @FXML
    private Label expiredLabel;

    private static final int EXPIRATION_YEARS = 1;// 使用期限为1年
    private static final String HARDCODED_FIRST_RUN_DATE = "2025-08-01"; // 硬编码的首次运行日期（格式：YYYY-MM-DD）

    @FXML
    public void initialize() {
        checkExpiration();

        if (mainTabPane.isVisible()) {
            loadTab("检测", "/com/zrc/japktool/tab0-view-checkgame.fxml");
            loadTab("签名", "/com/zrc/japktool/tab1-view-apksign.fxml");
            loadTab("转化", "/com/zrc/japktool/tab2-view-xapk2apk.fxml");
            loadTab("密钥", "/com/zrc/japktool/tab3-view-keystore.fxml");
            loadTab("安装", "/com/zrc/japktool/tab4-view-apkinstall.fxml");
            //loadTab("工程", "/com/zrc/japktool/tab5-view-fakerapk.fxml");
            loadTab("合并", "/com/zrc/japktool/tab6-view-apkmerge.fxml");
            loadTab("加固", "/com/zrc/japktool/tab7-view-apkjiagu.fxml");
        }
    }

    private void checkExpiration() {
        try {
            LocalDate firstRunDate = LocalDate.parse(HARDCODED_FIRST_RUN_DATE);
            LocalDate today = LocalDate.now();
            long daysBetween = ChronoUnit.DAYS.between(firstRunDate, today);
            if (daysBetween > 365 * EXPIRATION_YEARS) {
                // 超过使用期限
                mainTabPane.setVisible(false);
                expiredLabel.setVisible(true);
                expiredLabel.setText(String.format("您已经超过使用年限\n首次使用日期: %s\n已使用天数: %d", HARDCODED_FIRST_RUN_DATE, daysBetween));
            }
        } catch (Exception e) {
            e.printStackTrace();// 日期解析出错，默认允许使用
        }
    }

    private void loadTab(String tabName, String fxmlPath) {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource(fxmlPath));
            Node content = loader.load();

            Tab tab = new Tab(tabName);
            tab.setContent(content);
            tab.setClosable(false);
            mainTabPane.getTabs().add(tab);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}